package com.technology.education.ui.student.withdraw

import androidx.lifecycle.MutableLiveData
import com.huantansheng.easyphotos.models.album.entity.Photo
import com.technology.education.data.model.DurationWithdrawModel
import com.technology.education.ext.getAppViewModel
import com.technology.education.ext.toast
import com.technology.education.network.apiService
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.callback.databind.BooleanObservableField
import me.hgj.jetpackmvvm.callback.databind.StringObservableField
import me.hgj.jetpackmvvm.ext.request
import me.hgj.jetpackmvvm.state.ResultState

class WithdrawStudentViewModel : BaseViewModel() {
    val money = StringObservableField("0")
    val notifyText = StringObservableField("")
    var photoPath: Photo? = null
    val showLoading=MutableLiveData(false)

    /**
     * 申请退回保障金
     */
    val applyResult = MutableLiveData<ResultState<DurationWithdrawModel>>()

    /**
     * 最大可提现金额
     */
    var maxMoney = 0

    override fun getData() {
        super.getData()
        request({ apiService.exchangeRule() }, success = {
            maxMoney = it.pointToMoneyValue
            notifyText.set("当前积分最多可兑换${it.pointToMoneyValue}元")
        })
    }

    fun allMoney() {
        money.set(maxMoney.toString())
    }

    fun commit() {
        if (money.get().isEmpty()) {
            toast("请输入提现金额")
            return
        }
        if (money.get().toInt() > maxMoney) {
            toast("当前余额不足")
            return
        }
        if (photoPath == null) {
            toast("请上传微信收款码")
            return
        }
        showLoading.postValue(true)
        getAppViewModel().upload(listOf(photoPath!!)) {
            studentScoreWithdraw(it[0])
        }

    }

    /**
     * 学生积分兑换现金
     */
    private fun studentScoreWithdraw(url: String) {
        request({
            apiService.pointWithdraw(
                hashMapOf(
                    "value" to money.get(),
                    "wechatPayCode" to url
                )
            )
        }, applyResult, isShowDialog = true)
    }

}